<template>
  <div class="report-card flex ">
    <ul class="nav">
      <li v-for="(record, recordKey) in catalogMap" :key="recordKey" :class="{'active': activeCatalog === recordKey}" @click="goAnchor(recordKey)">{{ record.title }}</li>
    </ul>
    <div class="box-container">
      <el-form :model="form" label-width="170px" class="report-form" @scroll.native="handleScroll">
        <div v-for="(record, recordKey) in catalogMap" :key="recordKey" class="box">
          <div :class="['title', recordKey]">{{ record.title }}</div>
          <div class="content">
            <hw-store
              v-if="recordKey === 'hwStoreStatusInfos'"
              v-model="form[recordKey]"
              :disabled="status === 2 && !isEditing"
              :dict="dict"
              :title="record.title"
            />
            <multiple-form
              v-else-if="record.type === 'list'"
              v-model="form[recordKey]"
              :disabled="status === 2 && !isEditing"
              :record-key="recordKey"
              :dict="dict"
              :attrs="record.attrs"
            />
            <single-form
              v-else
              v-model="form[recordKey]"
              :disabled="status === 2 && !isEditing"
              :dict="dict"
              :attrs="record.attrs"
            />
          </div>
        </div>
      </el-form>

      <div v-if="status !== -1" class="footer">
        <div v-if="status !== 2" class="btn cancel" @click="onCancel">取消</div>
        <div v-if="status === 0" class="btn confirm" @click="onStart">启动</div>
        <div v-if="status === 1" class="btn confirm" @click="onConfirm">{{ status === 1 ? '暂存' : '保存' }}</div>
        <div v-if="status === 1" class="btn submit" @click="onSubmit">完成</div>
        <div v-if="status === 1" class="btn terminate" @click="onTerminate">终止</div>
        <template v-if="status === 2 && isAdmin">
          <div v-if="isEditing" class="btn cancel" @click="onCorrectCancel">取消</div>
          <div class="btn confirm" @click="onCorrect">更正</div>
        </template>
        <div v-if="status === 2" class="btn submit" @click="onExport">导出报表</div>
        <div v-if="status === 2 || status === -10" class="btn" @click="onExportAll">导出全部</div>
      </div>
    </div>
  </div>
</template>
<script>
import HwStore from './report/HwStore'
import MultipleForm from './report/MultipleForm'
import SingleForm from './report/SingleForm'

export default {
  name: 'ReportCard',
  components: { HwStore, SingleForm, MultipleForm },
  dicts: [
    'env_task_product_process',
    'env_system_has_or_not',
    'env_finish_status',
    'env_task_publish',
    'env_system_yes_no',
    'env_system_operation_status',
    'env_task_rain_sewage_problem',
    'env_task_gas_site_conditions',
    'env_task_accord'
  ],
  props: {
    reportInfo: {
      type: Object,
      required: true
    },
    isAdmin: Boolean,
    status: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      isEditing: false, // 是否处于更正状态
      form: {},
      catalogMap: {
        taskInfo: {
          title: '巡查基本信息',
          attrs: [
            { key: 'handlerName', title: '巡查人员', placeholder: '请输入巡查人员' },
            { key: 'position', title: '巡查地点' },
            { key: 'startTime', title: '巡查时间', type: 'datetime', placeholder: '选择日期' },
            { key: 'num', title: '本年度巡查次数' },
            { key: 'conclusion', title: '巡查小结', type: 'textarea' }
          ]
        },
        equipItems: {
          title: '设备情况', type: 'list',
          attrs: [
            { key: 'equipHisNum', title: '环评报告设备数量' },
            { key: 'equipCurNum', title: '巡查实际数量' },
            { key: 'equipNumDiff', title: '数量变化' },
            { key: 'files', title: '附件', type: 'file' }
          ]
        },
        productProcessInfo: {
          title: '生产工艺',
          attrs: [
            { key: 'productProcessStatus', title: '生产工艺变化情况', type: 'select', dictType: 'env_task_product_process', defaultValue: '无重大变化' },
            { key: 'productProcessRemark', title: '变化情况说明', depKey: 'productProcessStatus', depValue: '有重大变化', placeholder: '请输入内容' },
            { key: 'newWasteStatus', title: '新污染物情况', type: 'select', dictType: 'env_system_has_or_not', defaultValue: '无' },
            { key: 'newWasteRemark', title: '新污染物情况说明', depKey: 'newWasteStatus', depValue: '有', placeholder: '请输入内容' },
            { key: 'processAdvice', title: '针对变化的建议', type: 'textarea', placeholder: '请输入内容' }
          ]
        },
        ownerMonitorStatus: {
          title: '本年度自行监测',
          attrs: [
            { key: 'ownerMonitorStatus', title: '自行监测完成情况', type: 'select', dictType: 'env_finish_status', defaultValue: '已完成' }
          ]
        },
        planPublishStatus: {
          title: '执行报告发布',
          attrs: [
            { key: 'planPublishStatus', title: '执行报告发布情况', type: 'select', dictType: 'env_task_publish', defaultValue: '不涉及' }
          ]
        },
        mergencyInfo: {
          title: '应急预案',
          attrs: [
            { key: 'mergencyPlanStatus', title: '应急预案情况', type: 'select', dictType: 'env_system_has_or_not', defaultValue: '无要求' },
            { key: 'mergencyPlanChange', title: '是否需要变更', type: 'select', dictType: 'env_system_yes_no', depKey: 'mergencyPlanStatus', depValue: '有', defaultValue: '否' },
            { key: 'mergencyLagoonStatus', title: '应急池是否空置', type: 'select', dictType: 'env_system_yes_no', depKey: 'mergencyPlanStatus', depValue: '有', defaultValue: '是' }
          ]
        },
        wasteWaterInfo: {
          title: '废水产生',
          attrs: [
            { key: 'wasteWaterDesc', title: '生产废水产生情况' },
            { key: 'wasteWaterEquipStatus', title: '处理设施运转情况', type: 'select', dictType: 'env_system_operation_status', defaultValue: '无' },
            { key: 'wasteWaterEquipRemark', title: '异常说明', depKey: 'wasteWaterEquipStatus', depValue: '异常' },
            { key: 'drainageSignStatus', title: '有无废水排放口标志牌', type: 'select', dictType: 'env_system_has_or_not', defaultValue: '有' }
          ]
        },
        rainSewageInfo: {
          title: '雨污水情况',
          attrs: [
            { key: 'rainSewageStatus', title: '雨污水管网是否存在问题', type: 'select', dictType: 'env_task_rain_sewage_problem', defaultValue: '不存在' },
            { key: 'rainSewageRemark', title: '问题情况说明', placeholder: '请输入内容', depKey: 'rainSewageStatus', depValue: '其他' },
            { key: 'rainSewageSignStatus', title: '有无雨水排放口标志牌', type: 'select', dictType: 'env_system_has_or_not', defaultValue: '有' },
            { key: 'rainSewageErrorStatus', title: '是否有废水进入雨水管', type: 'select', dictType: 'env_system_yes_no', defaultValue: '否' },
            { key: 'files', title: '附件', type: 'file' }
          ]
        },
        gasSectionItems: {
          title: '废气收集情况', type: 'list',
          attrs: [
            { key: 'status', title: '现场情况', type: 'select', dictType: 'env_task_gas_site_conditions', defaultValue: '能有效收集' },
            { key: 'files', title: '附件', type: 'file', depKey: 'status', depValue: '未有效收集' }
          ]
        },
        gasPollutionItems: {
          title: '废气排放情况', type: 'list',
          attrs: [
            { key: 'exhaustPipelineStatus', title: '排气筒是否完好', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'fanStatus', title: '风机是否开启', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'exhaustHeightStatus', title: '排气筒高度是否满足要求', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'inspectionStatus', title: '检测口是否满足要求', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'handleEquipStatus', title: '处理设施是否开启', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'repairStatus', title: '是否按时维护', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'handleSourceStatus', title: '是否按时更换处理材料', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'otherUnusualStatus', title: '是否无其他异常', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'signboardStatus', title: '是否有标志牌', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'files', title: '附件', type: 'file' },
            { key: 'advice', title: '建议', type: 'textarea', placeholder: '请输入内容' }
          ]
        },
        taskNoiseInfo: {
          title: '噪声',
          attrs: [
            { key: 'majorNoiseSource', title: '主要噪声源', placeholder: '请输入主要噪声源' },
            { key: 'noiseStatus', title: '厂区是否有明显噪声', type: 'select', dictType: 'env_system_yes_no', defaultValue: '否' },
            { key: 'noiseMethodStatus', title: '噪声防止措施是否完善', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'noiseAdivce', title: '建议', type: 'textarea' }
          ]
        },
        solidWasteInfo: {
          title: '一般固废仓库',
          attrs: [
            { key: 'solidWasteStatus', title: '一般固废仓库是否满足要求', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'solidWasteBookStatus', title: '一般固废台账内容是否齐全', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'solidWasteNoteStatus', title: '一般固废标志是否张贴', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'solidWasteNoteAdvice', title: '建议', type: 'textarea', depKey: 'solidWasteNoteStatus', depValue: '否' },
            { key: 'files', title: '附件', type: 'file', depKey: 'solidWasteNoteStatus', depValue: '否' }
          ]
        },
        hwStoreStatusInfos: { title: '危废仓库管理情况', attrs: [] },
        hwData: {
          title: '危废管理资料情况',
          attrs: [
            { key: 'signContract', title: '是否签订了危废处置合同', type: 'select', dictType: 'sys_dict_yes_no', defaultValue: '是' },
            { key: 'deadlineStatus', title: '合同是否到期', type: 'select', dictType: 'env_system_yes_no', defaultValue: '否' },
            { key: 'standbookStatus', title: '台账是否齐全', type: 'select', dictType: 'env_system_yes_no', defaultValue: '是' },
            { key: 'typeChangeStatus', title: '危废种类是否发生变化', type: 'select', dictType: 'env_system_yes_no', defaultValue: '否' }
          ]
        }
      },

      clicked: false,
      activeCatalog: 'taskInfo',
      anchorOffsetMap: {} // 锚点从上到下的offsetTop数据
    }
  },
  watch: {
    reportInfo: {
      immediate: true,
      handler: function() {
        this.initFormData()
        setTimeout(this.initAnchorData, 100)
      }
    }
  },
  methods: {
    // 初始化anchor高度
    initAnchorData() {
      for (const key in this.catalogMap) {
        this.anchorOffsetMap[key] = document.querySelector(`.${key}`) ? document.querySelector(`.${key}`).offsetTop : 0
      }
    },

    goAnchor(catalog) {
      this.clicked = true
      this.activeCatalog = catalog
      const el = document.querySelector('.report-form')
      el.scrollTo({
        top: this.anchorOffsetMap[catalog] - 5,
        behavior: 'smooth'
      })
    },
    handleScroll(e) {
      const top = e.target.scrollTop
      let active = null
      for (const key in this.catalogMap) {
        if (top + 100 >= this.anchorOffsetMap[key]) {
          active = key
        }
      }
      if (this.clicked) {
        setTimeout(() => { this.clicked = false }, 1100)
      } else {
        this.activeCatalog = active
      }
    },

    isArray(val) {
      return Object.prototype.toString.apply(val).slice(8, -1).toLowerCase() === 'array'
    },
    isObject(val) {
      return Object.prototype.toString.apply(val).slice(8, -1).toLowerCase() === 'object'
    },
    initFormData() {
      const reportInfo = JSON.parse(JSON.stringify(this.reportInfo))
      for (const key in this.catalogMap) {
        const record = this.catalogMap[key]
        record.attrs.forEach(attr => {
          if (attr.defaultValue) {
            if (this.isArray(reportInfo[key])) {
              reportInfo[key].forEach(item => {
                item[attr.key] = item[attr.key] || attr.defaultValue
              })
            } else if (this.isObject(reportInfo[key])) {
              reportInfo[key][attr.key] = reportInfo[key][attr.key] || attr.defaultValue
            }
          }
        })
      }

      this.form = reportInfo
    },
    handleChange(data) {
      this.form = data
      this.initAnchorData()
    },

    getFormattedData() {
      const data = { ...this.form }
      if (data.productProcessInfo.productProcessStatus !== '有重大变化') {
        data.productProcessInfo.productProcessRemark = ''
      }
      if (data.productProcessInfo.newWasteStatus !== '有') {
        data.productProcessInfo.newWasteRemark = ''
      }
      if (data.mergencyInfo.mergencyPlanStatus !== '有') {
        data.mergencyInfo.mergencyPlanChange = '/'
        data.mergencyInfo.mergencyLagoonStatus = '/'
      }
      if (data.wasteWaterInfo.wasteWaterEquipStatus !== '异常') {
        data.wasteWaterInfo.wasteWaterEquipRemark = ''
      }
      if (data.rainSewageInfo.rainSewageStatus !== '其他') {
        data.rainSewageInfo.rainSewageRemark = ''
      }
      if (data.solidWasteInfo.solidWasteNoteStatus !== '否') {
        data.solidWasteInfo.solidWasteNoteAdvice = ''
      }
      if (data.productProcessInfo.productProcessStatus !== '有重大变化') {
        data.productProcessInfo.productProcessRemark = ''
      }
      if (data.productProcessInfo.newWasteStatus !== '有') {
        data.productProcessInfo.newWasteRemark = ''
      }

      return data
    },
    onCancel() {
      this.$router.back()
    },
    // 启动
    onStart() {
      this.$emit('start')
    },
    onCorrectCancel() {
      this.isEditing = false
    },
    onCorrect() {
      if (this.isEditing) {
        this.isEditing = false
        this.$emit('correct', {
          type: 'report',
          formData: this.getFormattedData()
        })
      } else {
        this.isEditing = true
      }
    },
    // 保存
    onConfirm() {
      this.$emit('confirm', {
        type: 'report',
        formData: this.getFormattedData()
      })
    },
    // 完成
    onSubmit() {
      this.$emit('submit', {
        type: 'report',
        formData: this.getFormattedData()
      })
    },
    // 终止
    onTerminate() {
      this.$emit('terminate')
    },
    onExport() {
      this.$emit('export', 'report')
    },
    onExportAll() {
      this.$emit('export', 'all')
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/variables.scss";

.report-card {
  height: 100%;
  overflow: hidden;
  background-color: #fff;
}
ul {
  list-style: none;
  margin: 0;
  padding: 0;
  border-right: 1px solid $border-color;
  overflow: auto;
  li {
      padding: 10px 12px;
      white-space: nowrap;
      cursor: pointer;
      &.active {
        color: $primary-color;
        border-left: 3px $primary-color;
        box-shadow: -1px 0 $primary-color;
      }
    }
}
.box-container {
  display: flex;
  flex-direction: column;
  flex-grow: 2;
  padding-top: 10px;
}
.report-form {
  margin-left: 20px;
  flex-grow: 2;
  overflow: auto;
}
.box {
  .title {
    position: relative;
    font-size: 14px;
    color: $label-color;
    line-height: 26px;
    padding-left: 10px;
    margin: 0 0 10px;
    text-align: initial;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 3px;
      bottom: 0;
      width: 3px;
      background-color: $primary-color;
      border-radius: 3px;
    }
  }
}
</style>

